package com.youlu.campus.website.service.impl;

import com.youlu.campus.website.entity.ActivityDescription;
import com.youlu.campus.website.entity.ActivityDescriptionPageQuery;
import com.youlu.campus.website.repositories.ActivityDescriptionRepository;
import com.youlu.campus.website.service.ActivityDescriptionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 活动简介服务实现类
 */
@Service
public class ActivityDescriptionServiceImpl implements ActivityDescriptionService {

    @Autowired
    private ActivityDescriptionRepository activityDescriptionRepository;

    @Resource(name = "websiteMongoTemplate")
    private MongoTemplate mongoTemplate;

    /**
     * 保存活动（新增或修改，根据 id 是否存在判断）
     *
     * @param activity 活动对象
     * @return 保存后的活动对象
     */
    @Override
    public ActivityDescription saveActivity(ActivityDescription activity) {
        if (StringUtils.isBlank(activity.getId())) {
            activity.setCreateTime(LocalDateTime.now());
        } else {
            activity.setUpdateTime(LocalDateTime.now());
        }


        return activityDescriptionRepository.save(activity);
    }

    /**
     * 根据 id 查询活动
     *
     * @param id 活动主键
     * @return 活动对象 Optional 包装，避免空指针
     */
    @Override
    public ActivityDescription getActivityById(String id) {
        return activityDescriptionRepository.findById(id).orElse(null);
    }

    @Override
    public Page<ActivityDescription> findByPageToAdmin(ActivityDescriptionPageQuery pageQuery) {
        Query query = new Query();
        if (StringUtils.isNotBlank(pageQuery.getTitle())) {
            query.addCriteria(Criteria.where("title").regex(pageQuery.getTitle(), "i"));
        }
        if (StringUtils.isNotBlank(pageQuery.getType())) {
            query.addCriteria(Criteria.where("type").is(pageQuery.getType()));
        }
        if (pageQuery.getEnabled() != null) {
            query.addCriteria(Criteria.where("enabled").is(pageQuery.getEnabled()));
        }
        if (pageQuery.getPlatform() != null) {
            query.addCriteria(Criteria.where("platform").is(pageQuery.getPlatform()));
        }
        //统计总条数（分页需要先查总数）
        long total = mongoTemplate.count(query, ActivityDescription.class);

        Pageable pageRequest = PageRequest.of(pageQuery.getPage() - 1, pageQuery.getPageSize(), Sort.by("createTime").descending());
        List<ActivityDescription> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            // 应用排序
            query.with(pageRequest.getSort());
            list = mongoTemplate.find(query, ActivityDescription.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);
    }

    @Override
    public Page<ActivityDescription> findByPageToWeb(ActivityDescriptionPageQuery pageQuery) {
        Query query = new Query();
        if (StringUtils.isNotBlank(pageQuery.getTitle())) {
            query.addCriteria(Criteria.where("title").regex(pageQuery.getTitle(), "i"));
        }
        if (StringUtils.isNotBlank(pageQuery.getType())) {
            query.addCriteria(Criteria.where("type").is(pageQuery.getType()));
        }
        if (pageQuery.getEnabled() != null) {
            query.addCriteria(Criteria.where("enabled").is(pageQuery.getEnabled()));
        }
        if (pageQuery.getPlatform() != null) {
            query.addCriteria(Criteria.where("platform").is(pageQuery.getPlatform()));
        }

        //统计总条数（分页需要先查总数）
        long total = mongoTemplate.count(query, ActivityDescription.class);

        Pageable pageRequest = PageRequest.of(pageQuery.getPage() - 1, pageQuery.getPageSize(), Sort.by("sort").descending());
        List<ActivityDescription> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            // 应用排序
            query.with(pageRequest.getSort());
            list = mongoTemplate.find(query, ActivityDescription.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);
    }

    /**
     * 根据 id 删除活动
     *
     * @param id 活动主键
     */
    @Override
    public void deleteActivity(String id) {
        activityDescriptionRepository.deleteById(id);
    }
}